import React, { Component } from 'react';
import { connect } from 'dva';
import find from 'lodash/find';
import memoizeOne from 'memoize-one';
import isEqual from 'lodash/isEqual';
import { Redirect } from 'umi';
import { getItem } from '@/utils/utils';

/**
 * 根据当前的history模式，提取pathname
 */
export function getPageQuery() {
  const arr = window.location.href.split('?');
  let result = '';
  if (arr.length > 1) {
    // eslint-disable-next-line prefer-destructuring
    result = arr[1];
  }
  return result;
}

/* eslint-disable */
/*
 * 删除url 指定的入参值
 */
export function delUrlParams(url, name) {
  //根据#号拆分
  let poundArr = url.split('#');
  //？拆分
  let questionArr = [];
  if (poundArr) {
    poundArr.forEach((element, index) => {
      if (index > 0) {
        element = '#' + element;
      }
      let tempArr = element.split('?');
      if (!tempArr) {
        return true;
      }
      tempArr.forEach((item, idx) => {
        //保留问号
        if (idx > 0) {
          item = '?' + item;
        }
        questionArr.push(item);
      });
    });
  } else {
    questionArr = url.split('?');
    if (questionArr) {
      questionArr.forEach((item, idx) => {
        if (idx > 0) {
          item = '?' + item;
        }
      });
    }
  }
  if (!questionArr) {
    return url;
  }
  //&符号的处理
  let andArr = [];
  questionArr.forEach((item, index) => {
    let andIdx = item.indexOf('&');

    if (andIdx <= -1) {
      andArr.push(item);

      return true;
    }
    let tempAndArr = item.split('&');
    tempAndArr.forEach((ele, idx) => {
      if (idx > 0) {
        ele = '&' + ele;
      }
      andArr.push(ele);
    });
  });
  let newUrl = '';
  andArr.forEach(item => {
    let nameIndex = item.indexOf(name + '=');
    //不拼接要删除的参数
    if (nameIndex > -1) {
      //保留第一个问号
      let questionIdx = item.indexOf('?');
      if (questionIdx == 0) {
        newUrl += '?';
      }
      return true;
    }
    newUrl += item;
  });
  return newUrl.replace(/\?\&/g, '?');
}
/* eslint-enable */
class Iframe extends Component {
  constructor(props) {
    super(props);
    this.findMenu = memoizeOne(this.findMenu, isEqual);
  }

  /**
   * 查找对应的菜单信息
   * @return {object|undefined}
   */
  findMenu = (menuCode, all) => {
    return find(all, { menuCode });
  };

  render() {
    const {
      match: {
        params: { menuCode },
      },
      location: { search },
      size,
      all,
    } = this.props;

    const menu = this.findMenu(menuCode, all);

    if (menu === undefined || !/^\[iframe\]http+/.test(menu.urlAddr)) {
      // throw new Error('urlAddr format is error or the menuCode is not in the menu');
      return <Redirect to="/404" />;
    }

    let address = menu.urlAddr.split('[iframe]')[1];
    const { sessionId, userCode } = getItem('user');

    // 判断当前的 url 是否包含 sysUserCode 关键入参 产商品需要
    let flag = false;
    const a = address.split('?')[1];
    if (a) {
      if (a.includes('sysUserCode')) {
        flag = true;
      } else {
        flag = false;
      }
    }

    address = delUrlParams(address, 'sysUserCode');

    // 根据原连接是否带?, 决定用什么符号追加 bss3SessionId
    if (address.indexOf('?') === -1) {
      if (userCode) {
        if (flag) {
          address = `${address}?bss3SessionId=${sessionId}&sysUserCode=${userCode}`;
        } else {
          address = `${address}?bss3SessionId=${sessionId}`;
        }
      } else {
        address = `${address}?bss3SessionId=${sessionId}`;
      }
    } else {
      /* eslint-disable */
      if (userCode) {
        if (flag) {
          address = `${address}&bss3SessionId=${sessionId}&sysUserCode=${userCode}`;
        } else {
          address = `${address}&bss3SessionId=${sessionId}`;
        }
      } else {
        address = `${address}&bss3SessionId=${sessionId}`;
      }
      /* eslint-enable */
    }

    // 补充当前location传入的query数据
    if (search !== '') {
      address = `${address}&${search.slice(1)}`;
    }

    return (
      <iframe
        title={menu.menuName}
        src={address}
        frameBorder="0"
        height={size.height - 4}
        width="100%"
        style={{ backgroundColor: '#fff' }}
      />
    );
  }
}

export default connect(({ menu, setting }) => ({
  all: menu.all,
  size: setting.size,
}))(Iframe);
